package com.jule.goldfast.game.gameUtil;

import com.jule.goldfast.game.model.PlayerInfo;
import com.jule.goldfast.base.enums.PlayerStateEnum;
import com.jule.goldfast.base.enums.TableStateEnum;
import com.jule.goldfast.game.network.protocol.TableInnerReq;
import com.jule.goldfast.game.play.AbstractTable;
import com.jule.goldfast.game.play.TableUtil;
import com.jule.goldfast.game.service.LogService;
import com.jule.goldfast.game.service.TableService;
import com.jule.goldfast.game.service.TimerService;
import com.jule.goldfast.game.vavle.notice.NoticeBroadcastMessages;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;

@Slf4j
public class GameLogic {

    /**
     * 游戏开始计时器
     *
     * @param table
     */
    public static void gameReady(final AbstractTable table) {
        table.setTableStateEnum(TableStateEnum.GAME_READY);
        //停止牌桌内正在进行的倒计时
        TimerService.getInstance().delTimerTask(table.getRoomTableRelation());

        NoticeBroadcastMessages.sendPlayerInNotice(table);

        table.setLoseUserIds(table.getInGamePlayerIds(""));

        log.debug("广播==游戏开始start：{}",System.currentTimeMillis());
        TimerService.getInstance().addTimerTask(
                table.getCommonConfig().getGameStartCountDownSec(),
                table.getRoomTableRelation(),
                new TableInnerReq(table.getPlayType() + "", table.getRoomId(), table.getTableId()) {
                    @Override
                    public void processImpl() throws Exception {
                        log.debug("广播==游戏开始end：  {}",System.currentTimeMillis());
                        betTimer(table);
                    }
                });

        //发送开局日志
        LogService.OBJ.sendGamestartLog(table);
        LogService.OBJ.sendGameStartPlayerLog(table);
    }

    /**
     * 下注计时器
     *
     * @param table
     */
    public static void betTimer(final AbstractTable table) {
        log.debug("下注操作");
        //停止牌桌内正在进行的倒计时
        TimerService.getInstance().delTimerTask(table.getRoomTableRelation());
        table.setTableStateEnum(TableStateEnum.BET); //修改桌面状态为下注中
        //累计回合数
        table.setGameWheelNumber(table.getGameWheelNumber()+1);
        table.getInGamePlayers().putAll(table.getInGamePlayersBySeatNum());
        long baseBetScore = table.getRoomConfig().getAnte();
        table.setLastActionTime(System.currentTimeMillis());
        //当没有其它程序触发提前终止计时器时，那么计时器倒计时完成后，将执行下面的自动下注
        Iterator<PlayerInfo> iter = table.getInGamePlayers().values().iterator();
        while (iter.hasNext()) {
            PlayerInfo player = iter.next();
            if (!player.getState().equals(PlayerStateEnum.already_bet)) {
                player.setState(PlayerStateEnum.already_bet);
                player.setTotalAlreadyBetScore4Hand(baseBetScore);
                player.setCurScore(player.getPlayScoreStore() - baseBetScore);
                table.getAlreadyBet().put(player.getPlayerId(), Double.valueOf(baseBetScore));
            }
        }
        giveCards(table);
    }

    /**
     * 发牌动画
     * @param table
     */
    public static synchronized void giveCards(AbstractTable table) {
        log.debug("给牌操作");
        //停止牌桌内正在进行的倒计时
        TimerService.getInstance().delTimerTask(table.getRoomTableRelation());
        //广播发牌51005
        NoticeBroadcastMessages.giveCardBoardcast(table);
        log.debug("广播==发牌时间end：  {}",System.currentTimeMillis());
        TimerService.getInstance().addTimerTask(
                table.getCommonConfig().getOpenCardsCD(),
                table.getRoomTableRelation(),
                new TableInnerReq(table.getPlayType() + "", table.getRoomId(), table.getTableId()) {
                    @Override
                    public void processImpl() {
                        log.debug("开始调用开牌操作");
                        log.debug("调用计时器，发牌动画" + table.getTableStateEnum() + ", tableInfo->" + TableUtil.toStringNormal(table));
                        table.setLastActionTime(System.currentTimeMillis());
                        openCards(table);
                    }
                }
        );
    }

    /**
     * @param table
     */
    public static synchronized void openCards(AbstractTable table) {
        log.debug("开牌操作");
        //停止牌桌内正在进行的倒计时
        TimerService.getInstance().delTimerTask(table.getRoomTableRelation());
        //若都操作了下注 则发牌
        table.pressCard();

        table.setTableStateEnum(TableStateEnum.OPEN_CARD);
        //通知客户端（发出所有人的牌）发出看牌协议及倒计时时间51033
        NoticeBroadcastMessages.pressCardBroadcast(table);
        log.debug("广播==开牌结束end：  {}",System.currentTimeMillis());
        TimerService.getInstance().addTimerTask(
                table.getCommonConfig().getSettleCD(),
                table.getRoomTableRelation(),
                new TableInnerReq(table.getPlayType() + "", table.getRoomId(), table.getTableId()) {
                    @Override
                    public void processImpl() {
                        log.debug("调用结算动画" + table.getTableStateEnum() + ", tableInfo->" + TableUtil.toStringNormal(table));
                        table.setLastActionTime(System.currentTimeMillis());
                        settleAnimation(table); //调用计时器，倒计时结算动画
                    }
                }
        );
    }

    /**
     * 结算动画倒计时
     *
     * @param table
     */
    public static void settleAnimation(final AbstractTable table) {
        log.debug("结算操作");
        table.setTableStateEnum(TableStateEnum.SETTLE_ANIMATION);
        //停止牌桌内正在进行的倒计时
        TimerService.getInstance().delTimerTask(table.getRoomTableRelation());
        //广播结算动画 && 结算51013
        NoticeBroadcastMessages.settleAnimationBroadcast(table);
        Iterator<PlayerInfo> iter = table.getAllPlayers().values().iterator();
        while (iter.hasNext()) {
            PlayerInfo playerInfo = iter.next();
            if (playerInfo != null) {
                playerInfo.resetGameingInfo();
            }
        }

        //修改桌子的状态 如果打完一句(多个回合)为空闲 否则为等待
        if(table.getGameWheelNumber() >= 5) {
            for (PlayerInfo player : table.getInGamePlayersBySeatNum().values()) {
                //强制玩家离桌，清除玩家数据
                table.returnLobby(player.getPlayerId(), false);
                NoticeBroadcastMessages.sendLeaveNotice(table,player);
            }
            table.setTableStateEnum(TableStateEnum.IDEL);
            table.setTableStatus();
            table.setGameWheelNumber(0);
            table.initTableStateAttribute();
            table.clearAllSeats();
        }else{
            table.setTableStateEnum(TableStateEnum.WAITFOR);
            //停止牌桌内正在进行的倒计时
            TimerService.getInstance().delTimerTask(table.getRoomTableRelation());
            TimerService.getInstance().addTimerTask(
                    table.getCommonConfig().getBetCountDownSec(),
                    table.getRoomTableRelation(),
                    new TableInnerReq(table.getPlayType() + "", table.getRoomId(), table.getTableId()) {
                        @Override
                        public void processImpl() {
                            TableService.getInstance().playGame(table); //开始游戏
                        }
                    }
            );
        }
        log.debug("当前桌子的轮数：{}，当前桌子的状态：{}",table.getGameWheelNumber(),table.getTableStateEnum());
    }

}